<script setup>
	import SongInfoShare from "./components/SongInfoShare.vue";
	import SongProgress from "./components/SongProgress.vue";
	import PlayController from "./components/PlayController.vue";
	import SongItem from "./components/SongItem.vue";
	import { useAduio } from "./hooks/useAduio";
	import { getSongs } from "../../apis/song.js";
	import { ref, onMounted, computed } from "vue";

	const { audio } = useAduio();
	const songs = ref([]);
	const currentPlayIndex = ref(0);

	const currentImg = computed(() => {
		const song = songs.value[currentPlayIndex.value];
		if (!song)
			return "https://p.aiu.pub/file/picture/20240401/4b2c61a9345afd82c31722b0e0ec6f52.jpg.webp";
		return song.cover;
	});
	onMounted(() => {
		getSongsData();
	});

	const getSongsData = async () => {
		const res = await getSongs();
		if (!res) return;
		const { data } = res;
		songs.value = data;
	};

	const onPlay = (index) => {
		console.log("index", index);
		if (audio) {
			audio.stop();
		}
		currentPlayIndex.value = index;
		const song = songs.value[index];
		console.log("song", songs);
		audio.src = song.url;
		audio.play();
	};

	const changeCurrent = (value) => {
		if (!audio) return;
		audio.seek(value);
	};

	const changePlay = (step) => {
		currentPlayIndex.value = currentPlayIndex.value + step;
		currentPlayIndex.value =
			currentPlayIndex.value < 0
				? songs.value.length - 1
				: currentPlayIndex.value;
		currentPlayIndex.value =
			currentPlayIndex.value >= songs.value.length
				? songs.value.length - 1
				: currentPlayIndex.value;
		onPlay(currentPlayIndex.value);
	};
</script>

<template>
	<view class="songs-wrapper">
		<div class="song">
			<image :src="currentImg" class="cover-img" />
		</div>
		<!--      歌名、分享、下载、保存-->
		<SongInfoShare v-bind="songs[currentPlayIndex]" />
		<!--      进度条-->
		<SongProgress :audio="audio" @changeCurrent="changeCurrent" />
		<!--      播放控制-->
		<PlayController
			:audio="audio"
			@change-last="changePlay(-1)"
			@change-next="changePlay(1)"
		/>
		<section class="songs-list">
			<h3 style="margin-bottom: 22px">Up Next</h3>
			<view
				class="songs-item"
				v-for="(song, i) in songs"
				@click="onPlay(i)"
				:key="i"
			>
				<SongItem v-bind="song" />
			</view>
		</section>
	</view>
</template>

<style lang="scss" scoped>
	.songs-wrapper {
		padding: 18px 27px;
		box-sizing: border-box;
		height: 100%;
		background-color: #000;
	}

	.song {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.cover-img {
		width: 288px;
		height: 234px;
		border-radius: 45px;
		object-fit: contain;
		margin-bottom: 23px;
	}
</style>
